package com.interview.two.service;

import com.interview.two.mapper.AccountMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileNotFoundException;

@Service
public class Service4 {

    @Resource
    private AccountMapper accountMapper;

    /**
     * 若是 非公共方法，加 @Transactional 将不会开启事务
     * 原因是：Spring为方法创建代理，添加事务通知，前提条件都是该方法是public
     * */
    @Transactional
    void transfer(int from, int to, int amount) throws FileNotFoundException {
        int fromBalance = accountMapper.findBalanceBy(from);
        if (fromBalance - amount >= 0) {
            accountMapper.update(from, -1 * amount);
            accountMapper.update(to, amount);
        }
    }
}